package cn.kgc.springcloud.controller;

import cn.kgc.springcloud.client.TagClient;
import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.entity.Tag;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.vo.ClazzVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author: mosin
 * @version: v1.0  2023/1/11
 */
@RestController
@RequestMapping("clazz")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @Autowired
    private TagClient tagClient;

    @GetMapping
    public List<ClazzVO> clazzList(){

        //  tagId  ->  Tag
        List<Clazz> clazzList = clazzService.list();

        List<ClazzVO> collect = clazzList.stream().map(clazz -> {
            ClazzVO clazzVO = new ClazzVO();
            BeanUtils.copyProperties(clazz, clazzVO);
            Integer tagId = clazz.getTagid();
            // 根据标签的id查询 标签详细信息
            Tag tag = tagClient.getById(tagId);
            clazzVO.setTag(tag);
            return clazzVO;
        }).collect(Collectors.toList());
        return collect ;
    }


    @PostMapping
    public Clazz  addClazz(String name, MultipartFile file, Integer tagId ){

        //实现文件上传操作
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename); //  png  jpg
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String lastFileName = uuid+"."+filenameExtension;

        // 创建File类型对象 执行文件上传的名字和路径
        File f = new File("D:/upload", lastFileName);
        Clazz clazz = new Clazz();
        try {
            file.transferTo(f);
            clazz.setName(name);
            clazz.setTagid(tagId);
            clazz.setPath(lastFileName);
            clazzService.save(clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return clazz;
    }

    @DeleteMapping("{id}")
    public String delete(@PathVariable  Integer id){
        clazzService.removeById(id);
        return "ok";
    }


    @GetMapping("{id}")
    public Clazz  getById(@PathVariable Integer id){
        return clazzService.getById(id);
    }
}
